/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file    usart.c
  * @brief   This file provides code for the configuration
  *          of the USART instances.
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2025 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "usart.h"

/* USER CODE BEGIN 0 */
#include <stdarg.h>
#include <string.h>
#include <stdio.h>
#include "main.h"
#include "tim.h"
uint8_t rx_buf[1] = {0};
uint8_t rx_buf2[1] = {0};
uint8_t rx_buf3[1] = {0};
uint8_t rx_buf5[1] = {0};



#define USART_REC_LEN    200          //  ����ͨ�Ž������ݵ�����������С
#define EN_USART1_RX 		 1             //  ʹ�ܣ�1��/��ֹ��0�����ڽ���
// 定义解析状态
typedef enum {
    PARSE_START,
    PARSE_MQTT_HEADER,
    PARSE_JSON,
    PARSE_CONTENT,
    PARSE_END
} ParseState;
unsigned char    USART_RXD_Buf[USART_REC_LEN];      //  ����ͨ�Ž��ձ�������Ĵ���
unsigned int     USART_RXD_Cnt;
/* USER CODE END 0 */

UART_HandleTypeDef huart1;

/* USART1 init function */

void MX_USART1_UART_Init(void)
{

  /* USER CODE BEGIN USART1_Init 0 */

  /* USER CODE END USART1_Init 0 */

  /* USER CODE BEGIN USART1_Init 1 */

  /* USER CODE END USART1_Init 1 */
  huart1.Instance = USART1;
  huart1.Init.BaudRate = 115200;
  huart1.Init.WordLength = UART_WORDLENGTH_8B;
  huart1.Init.StopBits = UART_STOPBITS_1;
  huart1.Init.Parity = UART_PARITY_NONE;
  huart1.Init.Mode = UART_MODE_TX_RX;
  huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  huart1.Init.OverSampling = UART_OVERSAMPLING_16;
  if (HAL_UART_Init(&huart1) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN USART1_Init 2 */

  /* USER CODE END USART1_Init 2 */

}

void HAL_UART_MspInit(UART_HandleTypeDef* uartHandle)
{

  GPIO_InitTypeDef GPIO_InitStruct = {0};
  if(uartHandle->Instance==USART1)
  {
  /* USER CODE BEGIN USART1_MspInit 0 */

  /* USER CODE END USART1_MspInit 0 */
    /* USART1 clock enable */
    __HAL_RCC_USART1_CLK_ENABLE();

    __HAL_RCC_GPIOA_CLK_ENABLE();
    /**USART1 GPIO Configuration
    PA9     ------> USART1_TX
    PA10     ------> USART1_RX
    */
    GPIO_InitStruct.Pin = GPIO_PIN_9;
    GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
    HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

    GPIO_InitStruct.Pin = GPIO_PIN_10;
    GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

    /* USART1 interrupt Init */
    HAL_NVIC_SetPriority(USART1_IRQn, 0, 0);
    HAL_NVIC_EnableIRQ(USART1_IRQn);
  /* USER CODE BEGIN USART1_MspInit 1 */

  /* USER CODE END USART1_MspInit 1 */
  }
}

void HAL_UART_MspDeInit(UART_HandleTypeDef* uartHandle)
{

  if(uartHandle->Instance==USART1)
  {
  /* USER CODE BEGIN USART1_MspDeInit 0 */

  /* USER CODE END USART1_MspDeInit 0 */
    /* Peripheral clock disable */
    __HAL_RCC_USART1_CLK_DISABLE();

    /**USART1 GPIO Configuration
    PA9     ------> USART1_TX
    PA10     ------> USART1_RX
    */
    HAL_GPIO_DeInit(GPIOA, GPIO_PIN_9|GPIO_PIN_10);

    /* USART1 interrupt Deinit */
    HAL_NVIC_DisableIRQ(USART1_IRQn);
  /* USER CODE BEGIN USART1_MspDeInit 1 */

  /* USER CODE END USART1_MspDeInit 1 */
  }
}

/* USER CODE BEGIN 1 */
// 定义设备 ID 和请求 ID 的缓冲区
char device_id[64] = {0};
char request_id[64] = {0};
char publed[256];
// 解析接收到的数据
void parse_received_data(uint8_t* data, uint16_t len) {
    static ParseState state = PARSE_START;
    static uint8_t content_value = 0; // 用于保存解析到的 content 字段的值
    static uint8_t json_buffer[128]; // 用于缓存 JSON 数据
    static uint16_t json_index = 0; // 记录当前写入位置

    for (uint16_t i = 0; i < len; i++) {
        switch (state) {
            case PARSE_START:
                // 查找 "+MQTTSUBRECV" 字符串
                if (data[i] == '+' && i + 11 < len && memcmp(&data[i], "+MQTTSUBRECV", 12) == 0) {
                    state = PARSE_MQTT_HEADER;
                    i += 11; // 跳过 "+MQTTSUBRECV"
                }
                break;

            case PARSE_MQTT_HEADER:
                // 跳过 MQTT 头部数据，直到找到 JSON 数据的起始标志 '{'
                if (data[i] == '{') {
                    state = PARSE_JSON;
                    json_index = 0; // 重置 JSON 缓冲区索引
                    json_buffer[json_index++] = data[i]; // 将 '{' 存入 JSON 缓冲区
                }
                break;

            case PARSE_JSON:
                // 将数据存入 JSON 缓冲区
                if (json_index < sizeof(json_buffer) - 1) {
                    json_buffer[json_index++] = data[i];
                } else {
                    // 缓冲区已满，重置状态
                    state = PARSE_START;
                    json_index = 0;
                }

                // 检查是否接收到完整的 JSON 数据（以 '}' 结束）
                if (data[i] == '}') {
                    json_buffer[json_index] = '\0'; // 添加字符串结束符
                    state = PARSE_CONTENT; // 进入解析 content 字段的状态
                }
                break;

            case PARSE_CONTENT:
                // 在 JSON 缓冲区中查找 "content" 字段
                char* content_ptr = strstr((char*)json_buffer, "\"content\":");
                if (content_ptr != NULL) {
                    content_ptr += 10; // 跳过 "\"content\":\"" 
                    // 获取 content 的值
                    if (*content_ptr == '0' || *content_ptr == '1') {
                        content_value = *content_ptr - '0';
                        state = PARSE_END;
                    }
                } else {
                    // 未找到 content 字段，重置状态
                    state = PARSE_START;
                }
                break;

            case PARSE_END:
                // 处理 led 的值
                if(content_value  == 0){
                    HAL_GPIO_WritePin(LED_GPIO_Port, LED_Pin, GPIO_PIN_SET);
                    sprintf(publed,"AT+MQTTPUB=0,\"$oc/devices/67bd7f9b8e04aa0690b7e606_shebei2/sys/properties/report\",\"{\\\"services\\\":[{\\\"service_id\\\":\\\"server\\\"\\,\\\"properties\\\":{\\\"led\\\":0}}]}\",0,0\r\n");        //		AT_write(pubco2);
                    ESP8266_SendCmd(publed, "OK");
                    //LED_OFF(); // 关闭 LED
                }else if (content_value  == 1) 
                {
                    HAL_GPIO_WritePin(LED_GPIO_Port, LED_Pin, GPIO_PIN_RESET);
                    sprintf(publed,"AT+MQTTPUB=0,\"$oc/devices/67bd7f9b8e04aa0690b7e606_shebei2/sys/properties/report\",\"{\\\"services\\\":[{\\\"service_id\\\":\\\"server\\\"\\,\\\"properties\\\":{\\\"led\\\":1}}]}\",0,0\r\n");        //		AT_write(pubco2);
                    ESP8266_SendCmd(publed, "OK");
                    //LED_ON(); // 点亮 LED
                }
                state = PARSE_START; // 重置状态
                break;
        }
    }
}
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) {
    if (huart->Instance == USART1) {
        // 检查缓冲区是否已满
        if (esp8266_cnt >= ESP8266_BUF_SIZE) {
            esp8266_cnt = 0; // 重置计数器
        }

        // 将接收到的数据存入缓冲区
        esp8266_buf[esp8266_cnt++] = rx_buf[0];

//        // 解析接收到的数据
//        parse_received_data(esp8266_buf, esp8266_cnt);

        // 重新启动串口接收中断
        HAL_UART_Receive_IT(&huart1, (uint8_t*)rx_buf, 1);
    }
}
//void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
//{		
//        if(huart->Instance == USART1)
//		{
//			if(esp8266_cnt >= sizeof(esp8266_buf))
//            {
//                esp8266_cnt = 0; //???????????
//            }                
//			esp8266_buf[esp8266_cnt++] = rx_buf[0];  
//        }
//            
//			HAL_UART_Receive_IT(&huart1, (uint8_t*)rx_buf, 1);	
//}

/*
************************************************************
*	?????????	Usart_SendString
*
*	?????????	???????????
*
*	?????????	USARTx????????
*				str????????????
*				len?????????
*
*	?????????	??
*
*	?????		
************************************************************
*/
void Usart_SendString(UART_HandleTypeDef *USARTx,  char *str)
{
	
	while(*str != '\0')
	{
		HAL_UART_Transmit(USARTx, (uint8_t *)str,1,1000);
		str++;
	}

}

/*
************************************************************
*	?????????	Usart_SendString
*
*	?????????	???????????
*
*	?????????	USARTx????????
*				str????????????
*				len?????????
*
*	?????????	??
*
*	?????		
************************************************************
*/
void Usart_SendString_8266(UART_HandleTypeDef *USARTx, unsigned char *str, unsigned short len)
{

	unsigned short count = 0;
	
	for(; count < len; count++)
	{
		HAL_UART_Transmit(USARTx, str++,1,1000);
	}

}

/*
************************************************************
*	?????????	UsartPrintf
*
*	?????????	????????
*
*	?????????	USARTx????????
*				fmt??????????
*
*	?????????	??
*
*	?????		
************************************************************
*/
void UsartPrintf(UART_HandleTypeDef *USARTx, char *fmt,...)
{

	unsigned char UsartPrintfBuf[296];
	va_list ap;
	unsigned char *pStr = UsartPrintfBuf;
	
	va_start(ap, fmt);
	vsnprintf((char *)UsartPrintfBuf, sizeof(UsartPrintfBuf), fmt, ap);							//?????
	va_end(ap);
	
	while(*pStr != 0)
	{
		
		HAL_UART_Transmit(USARTx, (uint8_t *)pStr++,1,1000);

	}

}

/* USER CODE END 1 */
